package com.zhiwang.planet.mvvm.viewmodel.loginv2

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Build
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.aop.util.Throttle
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.mvvm.model.request.LoginRequest
import com.zhiwang.planet.mvvm.model.request.SmsReq
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.ColdDownTextView
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus

class FinishRegisterViewModel : RegisterViewModel() {

    val deviceId = MutableLiveData<String>()

    lateinit var errorHandler: (Throwable) -> Unit


    var imei: String = ""

    fun getSmsCode(v: View) {

        val coldDownButton = v as ColdDownTextView

        val userName = username.value


        if (!checkInput(userName, "手机号不能为空"))
            return

        restApi.getSms(SmsReq(userName!!).apply { setTypeWxBindPhone() })
                .arrangeComplete(Action {
                    Toaster.message("验证码已发送")
                    coldDownButton.start()
                }, { errorHandler(it) })
    }

    fun finishBind() {

        val req = buildLoginReq()

        req.code = imei

        restApi.wxBindPhone(req)
                .arrange(Consumer {

                    TokenManager.saveToken(it)
                    EventBus.getDefault().post(LoginEvent())

                    context.suicideAfterTransition()
                }, Consumer {

                    errHandler(it)
                },
                        Action {

                        })
    }

    private fun buildLoginReq(): LoginRequest {


        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        var wifiName = wifiManager.connectionInfo?.ssid ?: ""

        if (wifiName.indexOf("\"") == 0 && wifiName.lastIndexOf("\"") == wifiName.lastIndex)
            wifiName = wifiName.substring(1, wifiName.lastIndex)

        return LoginRequest(
                phone = username.value!!,
                sms = smsCode.value!!,
                imei = deviceId.value!!,
                get_token = 1,
                androidVersion = Build.VERSION.RELEASE,
                appVersionName = BuildConfig.VERSION_NAME,
                wifiName = wifiName,
                deviceModel = Build.MODEL)
    }
}